import React, { useEffect, useMemo } from "react";
import { observer } from "mobx-react-lite";
import {
  View,
  StyleSheet,
  Dimensions,
  ActivityIndicator,
  RefreshControl,
  Text,
} from "react-native";
import { FlatGrid } from "react-native-super-grid";

import HomeTabView from "./HomeTabView";
import { TabModel } from "../screens/Home";
import PipeListItem from "./PipeListItem";

import PipeStore from "../store/pipeStore";

const screenWidth = Dimensions.get("window").width;

interface HomePipeViewProps {
  route: TabModel;
}

const tabStores: { [key: string]: PipeStore } = {};

const getStoreForTab = (key: string): PipeStore => {
  if (!tabStores[key]) {
    tabStores[key] = new PipeStore();
  }
  return tabStores[key];
};

const HomePipeView: React.FC<HomePipeViewProps> = observer(({ route }) => {

  const pipeStore = useMemo(() => getStoreForTab(route.key), [route.key]);
  
  const {
    itemHeight,
    pipeList,
    isRefreshing,
    isLoadingMore,
    hasMore,
    onRefresh,
    onSelectedItem,
    loadMoreData,
  } = pipeStore;

  useEffect(() => {
    pipeStore.routeKey = route.key;
    pipeStore.tabId = route.key;
    pipeStore.loadData();
  }, []);

  const _renderItem = ({ item }: { item: any }) => {
    return <PipeListItem item={item} itemHeight={itemHeight} />;
  };

  const renderFooter = () => (
    <>
      {isLoadingMore && <ActivityIndicator size="large" color="red" />}
      {!hasMore && !isLoadingMore && (
        <Text style={styles.footerText}>没有更多数据了</Text>
      )}
    </>
  );

  return (
    <View style={styles.container}>
      {route.subList.length > 0 && (
        <HomeTabView items={route.subList} onSelectedItem={onSelectedItem} />
      )}
      <FlatGrid
        spacing={8}
        itemDimension={(screenWidth - 24) / 2}
        data={pipeList}
        renderItem={_renderItem}
        refreshControl={
          <RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} />
        }
        onEndReached={loadMoreData}
        onEndReachedThreshold={0.2}
        ListFooterComponent={renderFooter}
      />
    </View>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white",
  },
  footerText: {
    paddingVertical: 20,
    textAlign: "center",
    fontSize: 14,
    color: "#888",
  },
});

export default HomePipeView;
